package com.ybkj.daijia.server.service.impl;

import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageImpl;
import com.ybkj.daijia.page.impl.PageRequest;
import com.ybkj.daijia.server.mapper.DriverGradeMapper;
import com.ybkj.daijia.server.model.DriverGrade;
import com.ybkj.daijia.server.service.DriverGradeService;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class DefaultDriverGradeService implements DriverGradeService {

    @Autowired
    private DriverGradeMapper driverGradeMapper;

    @Override
    public Page<DriverGrade> queryAll() {

        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());

        List<DriverGrade> content = driverGradeMapper
            .selectAll(Pager.getOffset(), Pager.getLimit());
        long total = driverGradeMapper.countAll();

        return new PageImpl<DriverGrade>(content, pageable, total);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DriverGrade createGrade(String name, Integer grade) {
        DriverGrade driverGrade = new DriverGrade();
        driverGrade.setName(name);
        driverGrade.setGrade(grade);
        driverGradeMapper.insert(driverGrade);
        return driverGrade;
    }

    @Override
    public DriverGrade findOne(Long id) {

        return driverGradeMapper.findById(id);
    }

    @Override
    public int update(DriverGrade dg) {

        return driverGradeMapper.updateById(dg);
    }

    @Override
    public int delete(Long id) {

        return driverGradeMapper.deleteById(id);
    }

    @Override
    public List<DriverGrade> findAll() {
        return driverGradeMapper.selectAll(null, null);
    }

    @Override
    public DriverGrade findOneByName(String name) {
        List<DriverGrade> driverGrades = driverGradeMapper.selectByName(name);
        if (!CollectionUtils.isEmpty(driverGrades)) {
            return driverGrades.get(0);
        } else {
            return null;
        }
    }

}
